//
//  PictureSelectorViewController.swift
//  SinaWeibo23
//
//  Created by apple on 16/2/25.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker

private let pictureSelectCellId = "pictureSelectCell"
private let coloumCount: CGFloat = 2
private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {
    
    //定义图片数组
    lazy var imageList = [UIImage]()
    
    lazy var selectedAssets = [PHAsset]()
    //构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        //计算cell的宽度
        let w = (ScreenWidth - (coloumCount + 1) * PictureCellMargin) / coloumCount
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        //设置组间距
        layout.sectionInset = UIEdgeInsets(top: PictureCellMargin, left: PictureCellMargin, bottom: 0, right: PictureCellMargin)
        //必须调用指定的构造函数
        super.init(collectionViewLayout: layout)
        
    }

    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: pictureSelectCellId)
    }

}

extension PictureSelectorViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //操作数据源本身 就可以达到 '这种'(微信添加图片) 效果
        //没有图片的时候 cell不会显示
        //达到最大选择范围之后 就不运行用户选择图片
        let detla = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureSelectCellId, forIndexPath: indexPath) as! PictureSelectCell
        //设置随机色 也是开发中经常用到的调试方式
        cell.backgroundColor = UIColor.randomColor()
        //指定代理
        cell.pictureCellDelegate = self
        
        //设置cell的图片
        //fatal error: Array index out of range
        // 数组的数量(从1开始) 和 indextPath.item(从0 开始) 相等的情况下
        if imageList.count == indexPath.item {
            //显示多余出来的那一条数据
            cell.image = nil
        } else {
            //数组内的数据
            cell.image = imageList[indexPath.item]
        }
       
        return cell
    }
}

extension PictureSelectorViewController: PictureSelectCellDelegate {
    //必选的协议方法 在swift中如果不实现 会报错
    func userWillDeletePicture(cell: PictureSelectCell) {
        printLog(__FUNCTION__)
        //删除图片
        //在数据源中线删除数据
        //确定点击的cell对应的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            imageList.removeAtIndex(indexPath.item)
            selectedAssets.removeAtIndex(indexPath.item)
            //在刷新collectionView
            
            collectionView?.reloadData()
        }
    }
    
    func userWillChosePicture() {
        printLog(__FUNCTION__)
        let picker = HMImagePickerController(selectedAssets: self.selectedAssets)
        //设置图像选择代理
        picker.pickerDelegate = self
        //设置目标图片的尺寸
        picker.targetSize = CGSize(width: 600, height: 600)
        picker.maxPickerCount = 9
        presentViewController(picker, animated: true, completion: nil)
    }
}

extension PictureSelectorViewController: HMImagePickerControllerDelegate {
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        //记录图像，方便在 CollectionView 显示
        self.imageList = images
        
        // 记录选中资源集合，方便再次选择照片定位
        if selectedAssets != nil {
            self.selectedAssets = selectedAssets!
        }
        //刷新视图
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//声明协议
//只有遵守NSObjectProtocol  才能够使用weak关键字
protocol PictureSelectCellDelegate: NSObjectProtocol {
    //声明协议方法
    func userWillChosePicture()
    // 一般的做法是将提供协议的对象回调回去
    func userWillDeletePicture(cell: PictureSelectCell)
}


//MARK: 自定义cell
class PictureSelectCell: UICollectionViewCell {
    
    //声明代理对象  一定要使用weak 修饰 防止循环引用
    weak var pictureCellDelegate: PictureSelectCellDelegate?
    
    //外界设置的图片属性
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = image == nil
            //给 addBtn设置图片
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //添加的监听方法
    @objc private func addBtnDidClick()  {
        //使用代理对象 调用协议方法
        if self.image != nil {
            //已经设置图片
            printLog("已经设置图片啦,不要再设啦")
            return
        }
        pictureCellDelegate?.userWillChosePicture()
    }
    
    //删除的监听方法
    @objc private func deleteBtnDidClick()  {
        pictureCellDelegate?.userWillDeletePicture(self)
    }
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(white: 0.95, alpha: 1)
        setupUI()
    }
    
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        //添加子视图
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //设置按钮的视图显示样式  本身知识按钮的显示样式  但是真正起作用的是按钮内部的imageView在显示图片
        addBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    
    //懒加载视图
    private lazy var addBtn: UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var deleteBtn: UIButton = UIButton(backImageName: nil, imageName: "compose_photo_close")
}
